package com.atlzk.group.order.service.impl;

import com.atlzk.common.utils.*;
import com.atlzk.group.order.dao.OrderDao;
import com.atlzk.group.order.entity.OrderEntity;
import com.atlzk.group.order.feign.TgouFeignService;
import com.atlzk.group.order.utils.IdWorker;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.atlzk.group.order.dao.GroupDao;
import com.atlzk.group.order.entity.GroupEntity;
import com.atlzk.group.order.service.GroupService;


@Service("groupService")
public class GroupServiceImpl extends ServiceImpl<GroupDao, GroupEntity> implements GroupService {

    @Autowired
    private OrderDao orderDao;

    @Autowired
    private TgouFeignService tgouFeignService;

    @Autowired
    private OrderServiceImpl orderServiceImpl;


    @Autowired
    private IdWorker idWorker;

    @Override
    public PageUtils queryPage(Map<String, Object> params,Long smsTgouId) {
        IPage<GroupEntity> page = this.page(
                new Query<GroupEntity>().getPage(params),
                new QueryWrapper<GroupEntity>().eq("sms_tgou_id",smsTgouId).eq("oms_group_status",1)
        );

        return new PageUtils(page);
    }

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<GroupEntity> page = this.page(
                new Query<GroupEntity>().getPage(params),
                new QueryWrapper<GroupEntity>()
        );

        return new PageUtils(page);
    }



    @SneakyThrows
    @Override
    public void openGroup(GroupEntity groupEntity) {
        //团购商品id  查询对应团购信息
        Long smsTgouId = groupEntity.getSmsTgouId();
        R r = tgouFeignService.byId(smsTgouId);
        Object tgou = r.get("tgou");
        HashMap <String, Object> map = (HashMap <String, Object>) tgou;
        System.out.println(map);
        //限购    1 正常购买  0 达到限制
        int astrict = orderServiceImpl.astrict(groupEntity.getUmsUserId(), groupEntity.getSmsTgouId(), (Integer) map.get("smsTgouNum"));
        if (astrict == 0 ) {
            System.out.println("达到购买限制");
            return;
        }
        //一个用户只能对一个商品开一个团
//        astrict限制
        List <GroupEntity> groupEntities = baseMapper.selectList(new QueryWrapper <GroupEntity>().eq("ums_user_id", groupEntity.getUmsUserId()).eq("sms_tgou_id", groupEntity.getSmsTgouId()).between("oms_group_status",0,1));
        if (groupEntities.size() > 0) {
            System.out.println("当前用户已经对该商品开过团,并且未结束");
            return;//终止方法进行
        }
        //group 信息完善  状态为  未进行     并添加
        groupEntity.setSmsTgouGroupNum((Integer) map.get("smsTgouGroupNum"));
        groupEntity.setOmsGroupPersonNum(0);
        //时间计算
        Date date = new Date();
        DateUtil dateUtil = new DateUtil(date,DateUtil.COMMON_PATTERN);
        dateUtil.addMinute((Integer) map.get("smsTgouDateUnit"));
        groupEntity.setOmsGroupCreateDate(date);
        groupEntity.setOmsGroupEndDate(dateUtil.toDate());
        //状态为  为未进行
        groupEntity.setOmsGroupStatus(0);
        baseMapper.insert(groupEntity);
        //添加返回id  拼团id
        Long groupId = groupEntity.getOmsGroupId();
        //添加订单  信息完善  状态为  未进行   并添加

        OrderEntity orderEntity = new OrderEntity();
        orderEntity.setOmsOrderId(idWorker.nextId());
        orderEntity.setUmsUserId(groupEntity.getUmsUserId());
        orderEntity.setOmsIsHeader(1);
        orderEntity.setSmsTgouId(groupEntity.getSmsTgouId());
        //拼团id
        orderEntity.setOmsGroupId(groupId);
        orderEntity.setPmsProductName((String) map.get("pmsProductName"));
        BigDecimal smsTgouPrice = ObjectToBigDecimalUtils.getBigDecimal(map.get("smsTgouPrice"));
        orderEntity.setSmsTgouPrice(smsTgouPrice);
        orderEntity.setOmsOrderNum(1);
        Date now = new Date();
        orderEntity.setOmsCreateDate(now);
        //还未付款   状态未进行
        orderEntity.setOmsOrderStatus(0);
        orderDao.insert(orderEntity);
    }

    /**
     * 定时器   每分钟监听一次
     * 1.监听订单创建时间内半小时内付款成团
     * 2.监听开团时间  有效时间内未成团  所有订单拼团失败   拼团表和订单表状态修改
     */
    @Scheduled(cron = "0 * * * * ? *")
    public void watch() {
        Date now = new Date();
        //查询到所有订单
        List <OrderEntity> orderEntities = orderDao.selectList(null);
        //查询到所有 团
        List <GroupEntity> groupEntities = baseMapper.selectList(null);
        //1.监听订单创建时间内半小时内付款成团
        orderEntities.forEach(orderEntity -> {
            DateUtil dateUtil = new DateUtil(orderEntity.getOmsCreateDate());
            dateUtil.addMinute(30);
            //订单过期  状态修改  状态 0.代付款 1.拼团中 2.待发货 3.拼团失败 4.订单过期
            if (dateUtil.toDate().getTime() < now.getTime()) {
                orderEntity.setOmsOrderStatus(4);
                orderDao.updateById(orderEntity);
            }
        });
        //2.监听开团时间  有效时间内未成团  所有订单拼团失败   拼团表和订单表状态修改
        groupEntities.forEach(groupEntity -> {
            //开团过期  状态 0:未进行  1.拼团中 2.拼团成功 3.拼团失败
            if (groupEntity.getOmsGroupEndDate().getTime() < now.getTime()) {
                groupEntity.setOmsGroupStatus(3);
                baseMapper.updateById(groupEntity);
                //查询对应订单  修改状态为 3.拼团失败
                List <OrderEntity> orderEntityList = orderDao.selectList(new QueryWrapper <OrderEntity>().eq("oms_group_id", groupEntity.getOmsGroupId()));
                orderEntityList.forEach(orderEntity -> {
                    orderEntity.setOmsOrderStatus(3);
                    orderDao.updateById(orderEntity);
                });

            }
        });
    }



}